package cn.huixh.blindbox.service.impl;

import cn.huixh.blindbox.service.IMailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.Future;


/**
 * @author huixh
 * @version 1.0
 * @date 2022/5/5 10:53
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class IMailServiceImpl implements IMailService {

    private final JavaMailSender mailSender;

    @Value("${spring.mail.properties.from}")
    private String from;
    @Value("${spring.mail.open:true}")
    private Boolean isOpen;

    @Async
    @Override
    public void waitSendOver(Future< ? > future, Runnable func) {
        try {
            future.get();
            func.run();
        } catch ( Exception e ) {
            log.error("等待异步任务结果时发生异常！", e);
        }

    }

    private void send(MimeMessage mail) {
        if (isOpen) {
            mailSender.send(mail);
            log.info("邮件已经发送。");
        } else {
            log.info("邮件发送暂时关闭！");
        }
    }

    private void send(SimpleMailMessage mail) {
        if (isOpen) {
            mailSender.send(mail);
            log.info("邮件已经发送。");
        } else {
            log.info("邮件发送暂时关闭！");
        }
    }

    /**
     * 简单文本邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    @Async
    @Override
    public Future< String > simpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        send(message);
        return new AsyncResult<>("邮件已经发送。");
    }

    /**
     * 发送HTML邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    @Async
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        //获取MimeMessage对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(from);
            messageHelper.setTo(subject);
            message.setSubject(subject);
            messageHelper.setText(content, true);
            mailSender.send(message);
            log.info("邮件已经发送。");
        } catch ( MessagingException e ) {
            log.error("发送邮件时发生异常！", e);
        }
    }
}
